<script setup lang="ts">
import axios from 'axios'
import { computed, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import type { UploadInstance, UploadProps, UploadRawFile } from 'element-plus'
import { ElMessage } from 'element-plus'
import { cloneDeep } from 'lodash-es'
import { addRankProject, getAllRegionList, importSaleRank } from '@fl/api/xf-api/xf-manage'
import useMonthlyRanges from '../../hooks/useMonthlyRanges'
import useWeeklyRanges from '../../hooks/useWeeklyRanges'
import useQuarterRanges from '../../hooks/useQuarterRanges'
import useYearRanges from '../../hooks/useYearRanges'

// 类型定义
type RankProjectForm = {
    rankTime: string | number
    rankType: string | number
    cityCode: string
    cityName: string
    leftAreaCode: string
    leftAreaName: string
    rightAreaCode: string
    rightAreaName: string
}

type DistrictItem = {
    id: number
    code: string
    name: string
}

type TimeRangeOption = {
    label: string
    value: string
    start?: string
    end?: string
}

type RankDayTypeOption = {
    label: string
    value: number
}

// Props 类型
const props = defineProps<{
    row?: Record<string, any>
    show: boolean
    title?: string
}>()

// Emits 类型
const emits = defineEmits<{
    (e: 'close'): void
}>()

// 响应式数据
const form = reactive<RankProjectForm>({
    rankTime: '',
    rankType: 1,
    cityCode: '420100000000',
    cityName: '武汉市',
    leftAreaCode: 'A01',
    leftAreaName: '全武汉',
    rightAreaCode: 'A01',
    rightAreaName: '全武汉',
})

const cityOptions = ref<DistrictItem[]>([])
const upload = ref<UploadInstance>()
const dialogVisible = ref(false)

// 时间范围 Hook
const { yearRanges } = useYearRanges()
const { quarterRanges } = useQuarterRanges()
const { months: monthlyRanges } = useMonthlyRanges({
    startYear: 2023,
    chineseFormat: true,
})
const { weeks: weeklyRanges } = useWeeklyRanges({
    startYear: 2023,
    weekStartsOnMonday: false,
})

const rankTimeOptions = ref<TimeRangeOption[]>(weeklyRanges.value)

// 筛选时间类型选项 时间类型（1周榜/2月榜/3季榜/4年榜）
const rankTypeOptions = ref<RankDayTypeOption[]>([
    { label: '周榜', value: 1 },
    { label: '月榜', value: 2 },
    { label: '季榜', value: 3 },
    { label: '年榜', value: 4 },
])
const formRef = ref()
const formRules = reactive({
    cityCode: [
        { message: '请选择城市', required: true, trigger: 'change' },
    ],
    rankType: [{
        message: '请选择时间类型',
        required: true,
        trigger: 'change',
    }],
    rankTime: [{
        message: '请选择时间',
        required: true,
        trigger: 'change',
    }],
})

// 方法定义
function statusTimeChange(timeType: number | undefined): void {
    if (timeType === undefined) {
        rankTimeOptions.value = []
        return
    }

    switch (timeType) {
        case 1:
            rankTimeOptions.value = weeklyRanges.value
            break
        case 2:
            rankTimeOptions.value = monthlyRanges.value
            break
        case 3:
            rankTimeOptions.value = quarterRanges.value
            break
        case 4:
            rankTimeOptions.value = yearRanges.value
            break
        default:
            rankTimeOptions.value = []
    }
}

async function getDistrictList(): Promise<void> {
    try {
        const res = await getAllRegionList()
        cityOptions.value = res.data as DistrictItem[]
    }
    catch (error) {
        ElMessage.error('获取地区列表失败')
        console.error(error)
    }
}

function selectCityChange(val) {
    if (val) {
        const cityItem = cityOptions.value.find((item) => {
            return item?.areaCode === val
        })

        if (cityItem) {
            form.cityCode = cityItem.areaCode
            form.cityName = cityItem.areaName
        }
    }
    else {
        form.areaCode = ''
        form.areaName = ''
    }
}

function closeDialog(): void {
    emits('close')
}

const uploadFileList = ref([])
function handleChange(file, fileList) {
    uploadFileList.value = fileList // 更新文件列表
}

const handleExceed: UploadProps['onExceed'] = (files) => {
    upload.value?.clearFiles()
    const file = files[0] as UploadRawFile
    upload.value?.handleStart(file)
}

function handleHttpRequest(params: { file: File }): void {
    const file = params.file
    const fileType = file.type
    const isExcel = fileType.includes('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        || fileType.includes('application/vnd.ms-excel')
    const isLt2M = file.size / 1024 / 1024 < 100

    if (!isExcel) {
        ElMessage.error('只能上传.xls,.xlsx格式的Excel文件!')
        return
    }
    if (!isLt2M) {
        ElMessage.error('只能上传小于100M的文件')
    }
    const formData = new FormData()
    formData.append('file', file)
    formData.append('city', form.cityName)
    formData.append('rankType', form.rankType)
    formData.append('rankTime', form.rankTime)
    console.log('上传文件:', formData)
    importSaleRank(formData).then((res) => {
        if (res.code === 200) {
            emits('close')
            ElMessage.success(res.msg)
        }
        else {
            ElMessage.error(res.msg)
        }
    })
}

function beforeUpload(file) {
    if (!file) {
        ElMessage.warning('请先上传文件')
        return false
    }
}

async function submit() {
    if (await formRef.value.validate()) {
        if (!form.rankTime) {
            ElMessage.warning('请选择具体时间')
            return false
        }
        if (uploadFileList.value?.length > 0) {
            upload.value!.submit()
        }
        else {
            ElMessage.warning('请先上传文件')
            return false
        }
    }
}

// 下载模板
const excelModelUrl = ref('https://public-obs-cdn.anjulian.com.cn/2025-07-18/247d6920-ce09-426d-a302-82bf7e9fb39d.xlsx')
function downloadExcel(name: string) {
    downloadFile(excelModelUrl.value, name)
}

function downloadFile(url, filename) {
    return axios
        .get(url, {
            responseType: 'blob',
        })
        .then((res) => {
            const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }) // 构造一个blob对象来处理数据，并设置文件类型
            if (window.navigator.msSaveOrOpenBlob) {
                // 兼容IE10
                navigator.msSaveBlob(blob, filename)
            }
            else {
                const href = URL.createObjectURL(blob) // 创建新的URL表示指定的blob对象
                const a = document.createElement('a')
                a.style.display = 'none'
                a.href = href // 指定下载链接
                a.download = filename // 指定下载文件名
                a.click()
                URL.revokeObjectURL(a.href) // 释放URL对象
            }
        })
}

// 生命周期
onMounted(() => {
    getDistrictList()
})

watch(() => props.show, (newVal) => {
    dialogVisible.value = newVal
}, { immediate: true })
</script>

<template>
    <el-dialog v-model="dialogVisible"
               :title="props.title"
               width="60%"
               draggable
               @close="closeDialog"
    >
        <el-form ref="formRef"
                 :validate-on-rule-change="false"
                 :model="form"
                 :rules="formRules"
                 class="area-select"
        >
            <el-row style="width:100%">
                <el-col :span="24">
                    <el-form-item label="时间类型"
                                  prop="rankType"
                    >
                        <el-col :span="12">
                            <el-select v-model="form.rankType"
                                       @change="statusTimeChange"
                            >
                                <el-option v-for="item in rankTypeOptions"
                                           :key="item.value"
                                           :label="item.label"
                                           :value="item.value"
                                />
                            </el-select>
                        </el-col>

                        <el-col :span="12">
                            <el-select v-model="form.rankTime">
                                <el-option v-for="item in rankTimeOptions"
                                           :key="item.value"
                                           :label="item.label"
                                           :value="item.value"
                                />
                            </el-select>
                        </el-col>
                    </el-form-item>
                </el-col>

                <el-col :span="24">
                    <el-form-item label="所在城市"
                                  prop="cityCode"
                    >
                        <el-select v-model="form.cityCode"
                                   clearable
                                   @change="selectCityChange"
                        >
                            <el-option v-for="item in cityOptions"
                                       :key="item.areaCode"
                                       :label="item.areaName"
                                       :value="item.areaCode"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="24">
                    <el-form-item label="上传文件"
                                  :required="true"
                    >
                        <el-upload ref="upload"
                                   class="upload-demo"
                                   accept=".xls,.xlsx"
                                   :http-request="handleHttpRequest"
                                   :limit="1"
                                   :before-upload="beforeUpload"
                                   :on-exceed="handleExceed"
                                   :auto-upload="false"
                                   @change="handleChange"
                        >
                            <template #trigger>
                                <el-button type="primary">
                                    选择文件
                                </el-button>
                            </template>

                            <div>
                                <el-link mb20
                                         type="primary"
                                         @click="downloadExcel('楼盘销量榜导入模板')"
                                >
                                    批量导入模板下载
                                </el-link>
                            </div>

                            <template #tip>
                                <div class="el-upload__tip text-red">
                                    只能上传xls,xlsx格式的Excel文件,且限制上传一个文件,新文件覆盖旧文件
                                </div>
                            </template>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <template #footer>
            <span class="dialog-footer">

                <el-button @click="closeDialog">
                    取消
                </el-button>

                <el-button type="primary"
                           @click="submit"
                >
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style lang="scss" scoped>
  :deep() {
    --vxe-primary-color: #da0004;
    --vxe-loading-color: #da0004;
}

:deep(.vxe-table--render-default .vxe-body--row.row--stripe) {
    background-color: #fff !important;
}
</style>
